package com.juneng.utils.wxpay;

import com.github.wxpay.sdk.WXPayConfig;
import org.springframework.util.ResourceUtils;

import java.io.*;

/**
 * 小程序 - 微信支付相关配置
 *  V2版微信支付
 * @author chang
 * app支付 appId 开放平台得appId
 *
 */
public class WxPayAppConfig implements WXPayConfig {

    //服务器证书放置位置 p12证书 （退款时使用）
//     public static String certPath = "src/main/resources/config/apiclient_cert.p12";  //需放置本地绝对路径
    public static String certPath = "/home/app/apiclient_cert.p12";  //服务器上的路径（项目包同目录下）
    //API KEY
    public static String apiKey = "3TYBMR1JTXY3R9XIJ4WOGL78QWZZX94C";
    //商户id
    public static String mchId = "1611821904";
    //APP支付 appId
    public static String appId = "wx5d710991ddf34609";

    //证书数据
    private byte[] certData;

    //私有化构造器 单例模式
    private WxPayAppConfig(){
        try{
            File file = ResourceUtils.getFile(certPath);
            InputStream certStream = new FileInputStream(file);
            this.certData = new byte[(int) file.length()];
            certStream.read(this.certData);
        } catch ( IOException e ){
            e.printStackTrace();
        }
//        File file = new File(certPath);
//        System.out.println(certPath);
//        System.out.println(file);

//        try (InputStream certStream = new FileInputStream(file)) {
//            this.certData = new byte[(int) file.length()];
//            certStream.read(this.certData);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

    }

    //单例对象
    private volatile static WxPayAppConfig singleton;

    //获取单例方法 双检锁模式
    public static WxPayAppConfig getInstance() {
        if (singleton == null) {
            synchronized (WxPayAppConfig.class) {
                if (singleton == null) {
                    singleton = new WxPayAppConfig();
                }
            }
        }
        return singleton;
    }

    @Override
    public String getAppID() {
        return appId;
    }

    @Override
    public String getMchID() {
        return mchId;
    }

    @Override
    public String getKey() {
        return apiKey;
    }

    @Override
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    @Override
    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
        return 10000;
    }


}
